// 工程级hvigorfile.ts文件
import { hvigor, HvigorNode, HvigorPlugin } from '@ohos/hvigor';
import { appTasks, OhosHarContext, OhosPluginId, Target } from '@ohos/hvigor-ohos-plugin';
import { FileUtil } from '@ohos/hvigor';

// 实现自定义插件
export function customPlugin(): HvigorPlugin {
  return {
    pluginId: 'customPlugin',
    context() {
      return {
        data: 'customPlugin xxx'
      };
    },
    async apply(currentNode: HvigorNode): Promise<void> {
      hvigor.nodesEvaluated(async () => {
        // 注册模块级任务
        harTask(currentNode);
      });
    }
  };
}
function harTask(currentNode: HvigorNode) {
  // 等待全部节点加载完成之后获取子节点信息
  currentNode.subNodes((node: HvigorNode) => {
    // 获取har模块上下文信息
    const harContext = node.getContext(OhosPluginId.OHOS_HAR_PLUGIN) as OhosHarContext;
    const moduleName = harContext?.getModuleName();
    harContext?.targets((target: Target) => {
      const targetName = target.getTargetName();
      const outputPath = target.getBuildTargetOutputPath();
      // 禁用任务
      node.getTaskByName(`${target.getTargetName()}@SignHar`)?.setEnable(false);
      let pack = node.getTaskByName(`${targetName}@PackageHar`)
      let dir = pack?.task?.taskTmpDir
      node.registerTask({
        // 任务名称
        name: `${targetName}@ProcessDoc`,
        // 任务执行逻辑主体函数
        run() {
          if(dir){
            FileUtil.copyFileSync(".gitignore", `${dir}/asd`);
            console.log('ProcessDoc done');
          }
        },
        // 配置前置任务依赖
        dependencies: [`${targetName}@ProcessHarArtifacts`],
        // 配置任务的后置任务依赖
        postDependencies: [`${targetName}@PackageHar`]
      });
    });
  });
}
export default {
  system: appTasks,  /* Built-in plugin of Hvigor. It cannot be modified. */
  plugins:[customPlugin()]         /* Custom plugin to extend the functionality of Hvigor. */
};